package me.tuyou.redission.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scripting.support.ResourceScriptSource;

import java.io.Serializable;

@EnableCaching
@Configuration
@EnableConfigurationProperties({RedisProperties.class, CacheProperties.class})
public class RedisConfig {

    @Bean(name = "redisTemplate")
    public RedisTemplate initRedisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }

    @Bean
    public DefaultRedisScript<String> defaultRedisScript() {
        DefaultRedisScript<String> defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setResultType(String.class);
        defaultRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/red_packet_reduce.lua")));
        return defaultRedisScript;
    }

//    @Bean
//    public RedissonClient redissonClient(RedisProperties properties){
//        Config conf = new Config();
//        //单节点模式
//        SingleServerConfig singleServerConfig = conf.useSingleServer();
//        //设置连接地址：redis://127.0.0.1:6379
//        singleServerConfig.setAddress("redis://" + properties.getHost() + ":" + properties.getPort());
//        //设置连接密码
//        singleServerConfig.setPassword(properties.getPassword());
//        //使用json序列化方式
//        JsonJacksonCodec codec = new JsonJacksonCodec();
//        conf.setCodec(codec);
//        RedissonClient redissonClient = Redisson.create(conf);
//        return redissonClient;
//    }
}
